package cool.taomu.toolkit.utils

import java.lang.annotation.Annotation
import java.lang.reflect.Method
import java.util.Set
import org.reflections.Reflections
import org.reflections.scanners.Scanner
import org.reflections.scanners.Scanners
import org.reflections.util.ConfigurationBuilder
import org.slf4j.LoggerFactory

class ReflectionsScanner {
	val static LOG = LoggerFactory.getLogger(ReflectionsScanner);

	def static Set<Class<?>> scanType(Class<? extends Annotation> annotation, String basePackage) {
		return scanType(annotation, basePackage, Scanners.TypesAnnotated)
	}

	def static Set<Class<?>> scanType(Class<? extends Annotation> annotation, String basePackage,
		Scanner ... scanners) {
		var cbuild = new ConfigurationBuilder()
		if (basePackage !== null) {
			cbuild.forPackages(basePackage)
		}
		cbuild.addScanners(scanners)
		var Reflections reflections = new Reflections(cbuild);
		if (scanners.findFirst[it.equals(Scanners.TypesAnnotated)] !== null) {
			var scanResult = reflections.getTypesAnnotatedWith(annotation);
			LOG.info("扫描到注解 {} ==> 类:{}", annotation.name, scanResult)
			return scanResult
		} else if (scanners.findFirst[it.equals(Scanners.MethodsAnnotated)] !== null) {
			var Set<Method> subscribeMethods = reflections.getMethodsAnnotatedWith(annotation);
			val result = newHashSet()
			for (Method method : subscribeMethods) {
				result.add(method.getDeclaringClass());
			}
			LOG.info("扫描到的 注解 {} ==> 类:{}", annotation.name, result)
			return result
		}
	}
}
